package com.lei.study.depth.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.RetryNTimes;

/**
 * <p>
 * session 过期处理
 * </p>
 *
 * @author <a href='mailto:17674030991@163.com'/>伍磊
 */
public class CuratorSessionExpireTest {

    public static void main(String[] args) {
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("localhost:2181")
                .connectionTimeoutMs(5000)
                .sessionTimeoutMs(5000)
                .retryPolicy(new RetryNTimes(3, 1000))
                .build();
        client.start();

        // 设置连接监听器，若连接丢失后重连成功进行对应数据处理
        client.getConnectionStateListenable().addListener(new ConnectionStateListener() {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                // 连接丢失 & 重新连接成功
                if (newState == ConnectionState.LOST) {
                    try {
                        if (client.getZookeeperClient().blockUntilConnectedOrTimedOut()) {
                            doTask();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            private void doTask() {

            }
        });
    }
}
